﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Configuration;
using Newtonsoft.Json;
using Opc.Ua;
using Opc.Ua.Client;


namespace Forging2
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        G_Variable g_Variable = new G_Variable();
        //OpcUaHelper.OpcUaClient G_OpcUaClient = new OpcUaHelper.OpcUaClient();

        //private bool ForgingWindowsIsOpen = false;

        Common.Forging.ForgingWindow ForgingWindow;
        Common.Heating.HeatingFurnaceWindow HeatingFurnaceWindow;
        Common.Rolling.RollingWindow RollingWindow;
        Common.AppInitialization localApp;

        private System.Threading.Thread thdBack;

        private void btnAddByCode_Click(object sender, RoutedEventArgs e)
        {

            ProcInitial();
            ProcName.MinHeight = Convert.ToDouble(g_Variable.MenuHeight);
            var rnd = new System.Random().Next(100, 500).ToString();
            if (TBT.Dispatcher.CheckAccess())
            {
                TBT.Text = rnd;
            }
            else
            {
                TBT.Dispatcher.Invoke(new Action(() =>
                {
                    TBT.Text = rnd;                    
                }));
            }
            Console.WriteLine(rnd);

            var app = new Common.AppInitialization();
            app.LoadConfig();
            app.ServiceRunnig();
            var nodes = new List<string>();
            Common.Const.HeatingPLCAddress.ForEach(a => nodes.Add(a.DB_NODEID));
            SubscriptionPLCValue(nodes.ToArray());
            GetHeatingCountValue();


        }

        

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            //this.Topmost = true;
            //this.WindowStyle = System.Windows.WindowStyle.None;
            //this.WindowState = System.Windows.WindowState.Maximized;
            //this.ResizeMode = System.Windows.ResizeMode.NoResize;
            //this.Left = 0;
            //this.Top = 0;
            //this.Width = System.Windows.SystemParameters.PrimaryScreenWidth;
            //this.Height = System.Windows.SystemParameters.PrimaryScreenHeight;
            //ProcInitial();
            
            Binding binding = new Binding();
            binding.Source = Common.Const.Front;
            binding.Path = new PropertyPath("Notification");
            BindingOperations.SetBinding(txbMessage, TextBlock.TextProperty, binding);
            localApp = new Common.AppInitialization();
            Task.Run(() => { localApp.LoadConfig(); });

            thdBack = new System.Threading.Thread(SetSatuts);
            thdBack.IsBackground = true;
            thdBack.Start();


        }

        private void ProcInitial()
        {
            g_Variable.MenuHeight = Properties.Settings.Default.MenuHeight.ToString();
            g_Variable.Test = "Test2";
            
            //ProcName.Height = 50;
        }

        private void DataBindings()
        {
            
        }

        public void  SubscriptionPLCValue(string[] nodeids)
        {
            Common.Const.OPCServer.OpcUaClient.AddSubscription(Environment.MachineName, nodeids, PLCValueSubCallback);
        }
        public void PLCValueSubCallback(string key, MonitoredItem monitoredItem, MonitoredItemNotificationEventArgs args)
        {
            if (key != Environment.MachineName)
            {
                Common.Const.Front. Notification = "机器名不匹配，订阅失败！";
                return;
            }

            GetHeatingTemperatureValue(monitoredItem.StartNodeId.ToString(), args);

        }
        public void GetHeatingTemperatureValue(string monitornode, Opc.Ua.Client.MonitoredItemNotificationEventArgs args)
        {
            var equipment = Common.Const.HeatingPLCAddress.Where(a => a.DB_NODEID == monitornode).FirstOrDefault();
            if (equipment is null)
            {
                Common.Const.Front .Notification = string.Format("没有设备包含此 {0} 节点地址！", monitornode);
                return;
            }
            var heatingfurnace = Common.Const.HeatingFurnaces.Where(a => a.GID == equipment.EQUIPMENT_GID).FirstOrDefault();
            MonitoredItemNotification notification = args.NotificationValue as MonitoredItemNotification;


            heatingfurnace.Temperatures = DataValue.IsGood(notification.Value) ? notification.Value.WrappedValue.Value.ToString() : "0";
            Console.WriteLine(heatingfurnace.Temperatures);
            if (heatingfurnace.Temperatures.ToUpper() == "TRUE" || heatingfurnace.Temperatures.ToUpper() == "FALSE") return;
            switch (heatingfurnace.CODE)
            {
                case "JRL0":
                    heatingfurnace.DisplayTemperatures(Temperatures0);
                    //heatingfurnace.GetInFurnaceCount();
                    //heatingfurnace.DisplayCount(Counts0);
                    break;
                case "JRL1":
                    heatingfurnace.DisplayTemperatures(Temperatures1);
                    //heatingfurnace.GetInFurnaceCount();
                    //heatingfurnace.DisplayCount(Counts1);
                    break;
                case "JRL2":
                    heatingfurnace.DisplayTemperatures(Temperatures2);
                    //heatingfurnace.GetInFurnaceCount();
                    //heatingfurnace.DisplayCount(Counts2);
                    break;
                case "JRL3":
                    heatingfurnace.DisplayTemperatures(Temperatures3);
                    //heatingfurnace.GetInFurnaceCount();
                    //heatingfurnace.DisplayCount(Counts3);
                    break;
                case "JRL4":
                    heatingfurnace.DisplayTemperatures(Temperatures4);
                    //heatingfurnace.GetInFurnaceCount();
                    //heatingfurnace.DisplayCount(Counts4);
                    break;
                default:
                    break;
            }
            //Common.Const.Front.Notification = "数据检测正在运行……";




        }

        public async void GetHeatingCountValue()
        {
            foreach (var heatingfurnaces in Common.Const.HeatingFurnaces )
            {
                switch (heatingfurnaces.CODE)
                {
                    case "JRL0":
                        await heatingfurnaces.GetInFurnaceCount();                        
                        heatingfurnaces.DisplayCount(Counts0);
                        break;
                    case "JRL1":
                        await heatingfurnaces.GetInFurnaceCount();
                        heatingfurnaces.DisplayCount(Counts1);
                        break;
                    case "JRL2":
                        await heatingfurnaces.GetInFurnaceCount();
                        heatingfurnaces.DisplayCount(Counts2);
                        break;
                    case "JRL3":
                        await heatingfurnaces.GetInFurnaceCount();
                        heatingfurnaces.DisplayCount(Counts3);
                        break;
                    case "JRL4":
                        await heatingfurnaces.GetInFurnaceCount();
                        heatingfurnaces.DisplayCount(Counts4);
                        break;
                    default:
                        break;
                }
            }
            
        }

        private void ProcName_Click(object sender, RoutedEventArgs e)
        {

        }

        private void Start_Click(object sender, RoutedEventArgs e)
        {
            if (!localApp.AppConfigReadied)
            {
                Common.Const.Front.Notification = "配置尚未载入完成，请稍后重新开始！";
                return;
            }
            Cursor= Cursors.AppStarting;
            //txbMessage.Text = "Beging.....";
            //var app = new Common.AppInitialization();
            //localApp.LoadConfig();
            localApp.ServiceRunnig();
            List<string> nodes = new List<string>();
            Common.Const.HeatingPLCAddress.ForEach(a => nodes.Add(a.DB_NODEID));
            SubscriptionPLCValue(nodes.ToArray());
            GetHeatingCountValue();
            Cursor = null;
            //Common.Const.Front.Notification = "数据检测正在运行……";
            
        }

       
        private void End_Click(object sender, RoutedEventArgs e)
        {
            if (Common.Const.OPCServer.OPCServerConnected)
            {
                Common.Const.OPCServer.CloseOPCServer();
            }
            Common.Const.Front.Notification = "数据检测已经停止！";
        }

        private void Quit_Click(object sender, RoutedEventArgs e)
        {
            if (Common.Const.OPCServer !=null && !Common.Const.OPCServer.OPCServerConnected)
            {
                Common.Const.OPCServer.CloseOPCServer();
            }
            App.Current.Shutdown();
        }

        private void HeatingFurnace_Click(object sender, RoutedEventArgs e)
        {
            foreach (Window win in this.OwnedWindows)
            {
                if (win.Tag.ToString() == "0")
                {
                    HeatingFurnaceWindow.Activate();
                    return;
                }
            }
            HeatingFurnaceWindow = new Common.Heating.HeatingFurnaceWindow();
            HeatingFurnaceWindow.Owner = this;
            HeatingFurnaceWindow.Tag = "0";
            HeatingFurnaceWindow.Show();
        }

        private void Forging_Click(object sender, RoutedEventArgs e)
        {
            foreach (Window win in this.OwnedWindows)
            {
                if (win.Tag.ToString() == "1")
                {
                    ForgingWindow.Activate();
                    return;
                }
            }
            ForgingWindow = new Common.Forging.ForgingWindow();
            //System.Windows.Forms.Integration.ElementHost.EnableModelessKeyboardInterop(ForgingWindow);
            ForgingWindow.Owner = this;
            ForgingWindow.Tag = "1";
            ForgingWindow.ShowDialog();
            
            
        }

        private void Rolling_Click(object sender, RoutedEventArgs e)
        {
            foreach (Window win in this.OwnedWindows)
            {
                if (win.Tag.ToString() == "2")
                {
                    RollingWindow.Activate();
                    return;
                }
            }
            RollingWindow = new Common.Rolling.RollingWindow();
            RollingWindow.Owner = this;
            RollingWindow.Tag = "2";
            RollingWindow.Show();
        }


        private void SetSatuts()
        {
            //Brush brush= new SolidColorBrush(Colors.Transparent);
            bool bl = false;
            //App.Current.Dispatcher.Invoke(new Action(() => { brush = RunSatuts.Fill.CloneCurrentValue(); }));
            while (true)
            {
                if (bl)
                {
                    Application.Current.Dispatcher.Invoke(new Action(() => {
                        if (Common.Const.OPCServer is null)
                        {
                            Satuts.Fill = new SolidColorBrush(Colors.Red);
                            return;
                        }
                        Satuts.Fill = Common.Const.OPCServer.OPCServerConnected ? new SolidColorBrush(Colors.Green) : new SolidColorBrush(Colors.Red); }));
                    System.Threading.Thread.Sleep(1500);
                }
                else
                {
                    Application.Current.Dispatcher.Invoke(new Action(() => { Satuts.Fill = new SolidColorBrush(Colors.Transparent); }));
                    System.Threading.Thread.Sleep(1000);
                }
                bl = !bl;

            }
        }
    }
}
